package com.example.back.Controller;

import com.example.back.Annotation.UserLoginToken;
import com.example.back.Entity.Auction;
import com.example.back.Entity.Product;
import com.example.back.NonRepEntity.ProductPictureList;
import com.example.back.Entity.User;
import com.example.back.Repository.AuctionRepository;
import com.example.back.Repository.ProductRepository;
import com.example.back.Repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 上传与下载图片的接口
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class UploadController {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private AuctionRepository auctionRepository;

    //上传头像
    @UserLoginToken
    @PostMapping("/avatar/{userId}")
    public boolean uploadAvatar(@RequestParam(value = "file") MultipartFile file, @PathVariable("userId") long userId) {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//提取后缀名
        String filePath = "/webWork/static/avatar/";//存储地址
        UUID uuid = UUID.randomUUID();
        fileName = uuid + suffixName;//通过UUID获取随机名称

        User Tuser = userRepository.findUserByUserId(userId);
        //删除原先存在的图片
        String oldAvatarName = Tuser.getAvatarUUId();
        String oldPath = filePath + oldAvatarName;
        File oldAvatar = new File(oldPath);
        if (oldAvatar.exists()) {
            oldAvatar.delete();
        }
        //设定新的图片
        Tuser.setAvatarUUId(uuid.toString() + suffixName);
        userRepository.save(Tuser);
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {//如果不存在的话则新建文件夹
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //上传拍卖图片
    @UserLoginToken
    @PostMapping("/auc/{pictureType}/{auctionId}")
    public boolean uploadAuction(@RequestParam(value = "file") MultipartFile file,
                                 @PathVariable("auctionId") long auctionId,
                                 @PathVariable("pictureType") String pictureType) {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//提取后缀名
        String filePath = "/webWork/static/auction/";//存储地址
        UUID uuid = UUID.randomUUID();
        fileName = uuid + suffixName;//通过UUID获取随机名称

        Auction auction = auctionRepository.findAuctionByAuctionId(auctionId);
        //设定新的图片
        if (pictureType.equals("auctionCover")) {
            auction.setCoverUUID(uuid.toString() + suffixName);
        } else {
            auction.setPictureUUID(uuid.toString() + suffixName);
        }
        auctionRepository.save(auction);
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {//如果不存在的话则新建文件夹
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //上传商品图片
    //先创建商品，然后才能获取到productId，
    @UserLoginToken
    @PostMapping("/pro/{pictureType}/{productId}")
    public boolean uploadProductImg(@RequestParam(value = "file") MultipartFile file,
                                    @PathVariable("productId") long productId,
                                    @PathVariable("pictureType") String pictureType) {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//提取后缀名
        String filePath = "/webWork/static/product/";//存储地址
        UUID uuid = UUID.randomUUID();
        fileName = uuid + suffixName;//通过UUID获取随机名称

        Product product = productRepository.findProductByProductId(productId);
        //设定新的图片
        if (pictureType.equals("productCover")) {
            product.setCoverUUID(uuid.toString() + suffixName);
        } else {
            product.setPictureUUID(uuid.toString() + suffixName);
        }
        productRepository.save(product);
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {//如果不存在的话则新建文件夹
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //根据fileType去获取图片
    @UserLoginToken
    @GetMapping("/sig/{fileType}/{fileName}")
    public ResponseEntity<byte[]> downloadProductCover(@PathVariable("fileType") String fileType,
                                                       @PathVariable("fileName") String fileName) throws IOException {
        String filePath = "/webWork/static/" + fileType + "/" + fileName;
        InputStream loadStream = new FileInputStream(new File(filePath));
        byte[] body = null;
        body = new byte[loadStream.available()];//转为字节数组以传输
        loadStream.read(body);
        fileName = new String(fileName.getBytes("gbk"), "iso8859-1");//防止中文乱码
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=" + fileName);
        HttpStatus statusCode = HttpStatus.OK;//设定返回状态码
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }

    //获取多张图片，前端不显示，已废弃
    @Deprecated
    @UserLoginToken
    @PostMapping("/list/productCoverList")
    public List<ResponseEntity<byte[]>> downloadPictureList(@RequestBody ProductPictureList productCoverList) throws IOException {
        log.info("ENTER");
        log.info(productCoverList.getProductCoverUUIDList().get(0));
        List<String> productCoverUUIDList = productCoverList.getProductCoverUUIDList();
        List<ResponseEntity<byte[]>> result = new ArrayList<>();
        for (int i = 0; i < productCoverUUIDList.size(); i++) {
            String fileName = productCoverUUIDList.get(i);
            String filePath = "/webWork/static/product/" + fileName;
            InputStream loadStream = new FileInputStream(new File(filePath));
            byte[] body = null;
            body = new byte[loadStream.available()];//转为字节数组以传输
            loadStream.read(body);
            fileName = new String(fileName.getBytes("gbk"), "iso8859-1");//防止中文乱码
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment;filename=" + fileName);
            HttpStatus statusCode = HttpStatus.OK;//设定返回状态码
            ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
            result.add(response);
        }
        return result;
    }
}
